package net.oschina.j2cache;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.SecureRandom;

/**
 * 命令消息封装
 *
 * @author Winter Lau(javayou@gmail.com)
 */
public class Command {
  public static final byte OPT_JOIN = 0x01; // 加入集群
  public static final byte OPT_EVICT_KEY = 0x02; // 删除缓存
  public static final byte OPT_CLEAR_KEY = 0x03; // 清除缓存
  public static final byte OPT_QUIT = 0x04; // 退出集群
  private static final Logger log = LoggerFactory.getLogger(Command.class);
  private int src;
  private int operator;
  private String region;
  private String[] keys;

  public Command() {} // just for json deserialize , dont remove it.

  public Command(byte o, String r, String... keys) {
    this.operator = o;
    this.region = r;
    this.keys = keys;
  }

  public static int genRandomSrc() {
    long ct = System.currentTimeMillis();
    SecureRandom rndSeed = new SecureRandom();
    return (int) (rndSeed.nextInt(10000) * 1000 + ct % 1000);
  }

  public static Command join() {
    return new Command(OPT_JOIN, null);
  }

  public static Command quit() {
    return new Command(OPT_QUIT, null);
  }

  public static Command parse(String json) {
    try {
      return JSON.parseObject(json, Command.class);
    } catch (JSONException e) {
      log.warn("Failed to parse j2cache command: {}", json, e);
    }
    return null;
  }

  public int getOperator() {
    return operator;
  }

  public void setOperator(int operator) {
    this.operator = operator;
  }

  public String getRegion() {
    return region;
  }

  public void setRegion(String region) {
    this.region = region;
  }

  public String[] getKeys() {
    return keys;
  }

  public void setKeys(String[] keys) {
    this.keys = keys;
  }

  public int getSrc() {
    return src;
  }

  public void setSrc(int src) {
    this.src = src;
  }

  @Override
  public String toString() {
    return json();
  }

  public String json() {
    return JSON.toJSONString(this);
  }
}
